from rest_framework.views import APIView
from luffy.libs.geetest import GeetestLib
from django.conf import settings
import random
from rest_framework.response import Response
from luffy.libs.yuntongxun.sms import CCP
from django_redis import get_redis_connection
from .serializers import UserModelSerializer, UserOrderModelSerializer
from rest_framework.generics import CreateAPIView, RetrieveAPIView
from .models import User
from rest_framework.permissions import IsAuthenticated


class UserAPIView(CreateAPIView):
    serializer_class = UserModelSerializer
    queryset = User.objects.all()


class CaptchaAPIView(APIView):
    gt = GeetestLib(settings.PC_GEETEST_ID, settings.PC_GEETEST_KEY)
    redis = get_redis_connection('default')

    def get(self, request):
        user_id = '%06d' % random.randint(1, 9999)
        status = self.gt.pre_process(user_id)
        # request.session[self.gt.GT_STATUS_SESSION_KEY] = status
        # request.session["user_id"] = user_id
        self.redis.setex(self.gt.GT_STATUS_SESSION_KEY, 10 * 60, status)
        self.redis.setex('user_id', 10 * 60, user_id)

        response_str = self.gt.get_response_str()
        return Response(response_str)

    def post(self, request):
        challenge = request.POST.get(self.gt.FN_CHALLENGE, '')
        validate = request.POST.get(self.gt.FN_VALIDATE, '')
        seccode = request.POST.get(self.gt.FN_SECCODE, '')
        # status = request.session[self.gt.GT_STATUS_SESSION_KEY]
        # user_id = request.session["user_id"]
        status = self.redis.get(self.gt.GT_STATUS_SESSION_KEY)
        user_id = self.redis.get('user_id')
        if status:
            result = self.gt.success_validate(challenge, validate, seccode, user_id)
        else:
            result = self.gt.failback_validate(challenge, validate, seccode)
        return Response({'message': result})


class SMSAPIView(APIView):
    def get(self, request, mobile):
        redis = get_redis_connection('sms_code')
        try:
            interval = redis.get('%s_interval' % mobile)
            if interval:
                return Response({'result': '-1'})
        except:
            pass
        ccp = CCP()
        sms_code = '%04d' % random.randint(1, 9999)
        result = ccp.send_template_sms(mobile, [sms_code, 5], 1)

        if not result:
            redis.setex('%s_sms_code' % mobile, 5 * 60, sms_code)
            redis.setex('%s_interval' % mobile, 60, 1)
        return Response({'result': result})


class UserOrderAPIView(RetrieveAPIView):
    # permission_classes = [IsAuthenticated]
    serializer_class = UserOrderModelSerializer
    queryset = User.objects.all()
